<template>
  <div class="machine-info">
    <h2>机器信息</h2>
    <el-form :inline="true" class="search-form">
      <el-form-item>
        <el-input v-model="searchNumber" placeholder="请输入机器编号" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>
    <div class="machine-cards">
      <el-card v-for="machine in machineStore.machines" :key="machine.id" class="machine-card" shadow="hover" @click="handleRowClick(machine)">
        <div class="card-content">
          <div><strong>机器编号 : </strong> {{ machine.number }}</div>
          <div><strong>机器名称 : </strong> {{ machine.name }}</div>
          <div><strong>类型 : </strong> {{ machine.type }}</div>
          <div><strong>状态 : </strong>
            <el-tag :type="getStatusTagType(machine.status)">
              {{ machine.status === 'NORMAL' ? '正常' : machine.status === 'FAULT' ? '故障' : '维护中' }}
            </el-tag>
          </div>
        </div>
      </el-card>
      <div v-if="!machineStore.machines.length" class="empty-text">暂无机器数据</div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useMachineStore } from '@/stores/machine';
import { useUserStore } from '@/stores/user';
import { useRouter } from 'vue-router';

const router = useRouter();
const machineStore = useMachineStore();
const userStore = useUserStore();

const searchNumber = ref('');

const handleSearch = async () => {
  try {
    machineStore.setFilters({
      ownerId: userStore.user?.id,
      machineNumber: searchNumber.value,
    });

    if (!searchNumber.value) {
      ElMessage.warning('请输入机器编号');
      return;
    }

    await machineStore.fetchMachines();
  } catch (error) {
    ElMessage.error('搜索失败');
    console.error(error);
  }
};

const handleRowClick = (machine: any) => {
  router.push(`/machine/detail/${machine.id}`);
};

const getStatusTagType = (status: string) => {
  return status === 'NORMAL' ? 'success' : status === 'FAULT' ? 'danger' : 'warning';
};

onMounted(async () => {
  try {
    machineStore.setFilters({
      ownerId: userStore.user?.id,
    });
    await machineStore.fetchMachines();
  } catch (error) {
    ElMessage.error('获取机器列表失败');
    console.error(error);
  }
});
</script>

<style scoped>
.machine-info {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.search-form {
  margin-bottom: 20px;
}

.machine-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.machine-card {
  cursor: pointer;
  transition: all 0.3s;
}

.machine-card:hover {
  transform: translateY(-5px);
}

.card-content div {
  margin-bottom: 10px;
}

.card-content strong {
  color: #606266;
}

.empty-text {
  text-align: center;
  color: #999;
  padding: 20px;
}
</style>